package com.wcsy.myblog.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.wcsy.myblog.dao.UserMapper;
import com.wcsy.myblog.entity.Article;
import com.wcsy.myblog.entity.JsonResult;
import com.wcsy.myblog.entity.User;
import com.wcsy.myblog.service.IArticleService;
import com.wcsy.myblog.service.IUserService;
import com.wcsy.myblog.service.serviceImpl.NumServiceImpl;
import com.wcsy.myblog.service.serviceImpl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.DoubleStream;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(description = "用户信息")
@ApiModel()
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    HttpSession session;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    NumServiceImpl numService;
    @Autowired
    IArticleService iArticleService;
    @Autowired
    UserMapper userMapper;


    /**
     * @apiNote 判断登陆
     * @param user  手机号登陆，
     * */
    @ApiOperation("判断登陆")
    @PostMapping("/login")
    public JsonResult login(@RequestBody User user){
        UsernamePasswordToken token = new UsernamePasswordToken(user.getPhNumber(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
                subject.login(token); //登陆成功
            User user1 = (User) session.getAttribute("user");
            return new JsonResult(200,"登陆成功",user1);
        }catch (Exception ex){
          return new JsonResult(500,"账号或密码错误","");
        }
    }

    /**
     * @apiNote  注册
     * @param user 用户信息
//     * @param code 用户输入的验证码
//     * @param file 上传的文件
     * @return
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public JsonResult register(@RequestBody User user,int code){
        try {
            if (session.getAttribute("ImgCode").equals(code)){
            iUserService.insertlist(user);
            return new JsonResult(200,"注册成功","");
            }
            return new JsonResult(500,"验证码错误","");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(500,"注册失败","");
        }
    }
    /**
     * 更改用户的头像
     */
    @ApiOperation("修改用户的头像")
    @PostMapping("updateImg")
    public JsonResult updateImg(@RequestParam(value = "pic", required = false) MultipartFile file){
        User user = (User) session.getAttribute("user");
//        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", 1));
        String page = numService.getfile(file);
        user.setUserImg(page);
        try {
            iUserService.update(user,new QueryWrapper<User>().eq("user_id",user.getUserId()));
            return new JsonResult(200,"修改图片成功","");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(500,"修改图片失败","");
        }
    }

    /**
     * @apiNote  图片验证码
     * @throws IOException
     */
    @ApiOperation("图片验证码")
    @GetMapping("/code")
    public void code() throws IOException {
        userService.createcode();
    }

    /**
     * @apiNote  根据邮箱改密码之判断邮箱是否正确"
     * @param mail  邮箱
     * @return
     * @throws MessagingException
     */
    @ApiOperation("根据邮箱改密码之判断邮箱是否正确")
    @GetMapping("/selectMail")
    public JsonResult updateEmilPassword( String mail) throws MessagingException {
        session.setAttribute("emailPassword",mail);
        try {
            int code = userService.mailVer(mail);
            return  new JsonResult(200,"邮箱验证成功",code);
        } catch (MessagingException e) {
            e.printStackTrace();
            return new JsonResult(500,"邮箱验证失败","");
        }
    }

    /**
     * 生成手机短信验证码
     * @param tel 手机号
     * @return
     */
    @ApiOperation("手机短信验证码")
    @GetMapping("/codetel")
    public JsonResult code(@RequestBody String tel){  //tel是用户输入的手机号，
        session.setAttribute("telPassword",tel);
        try {
            int codepel = userService.codepel(tel);
            return new JsonResult(200,"发送短信验证码成功",codepel);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(500,"生成短信验证码失败",null);
        }
    }
    /**
     * @apiNote 忘记密码修改密码
     * @param password 新密码
     * @return
     */
    @ApiOperation("忘记密码修改密码")
    @GetMapping("/updatePassword")
    public JsonResult updatePassword(@RequestBody String password){
        String email = (String) session.getAttribute("emailPassword");
        String tel = (String) session.getAttribute("telPassword");
        User user = new User();
        if (email != null){
             user = iUserService.getOne(new QueryWrapper<User>().eq("mail", email));
        }else if (tel != null){
            user = iUserService.getOne(new QueryWrapper<User>().eq("ph_number", tel));
        }
        System.out.println("用户加密前的密码："+password);
       String pswd = new SimpleHash("md5",password, ByteSource.Util.bytes(user.getUserName()),5).toString();
        user.setPassword(pswd);
        boolean update = iUserService.update(user,new QueryWrapper<User>().eq("user_name",user.getUserName()));
          if (update){
              return  new JsonResult(200,"修改密码成功",password);
          }
          return new JsonResult(500,"修改密码失败",null);
    }

    /**
     * @apiNote 用户正常修改密码
     * @param passWd  原始密码
     * @param passWord  新密码
     * @return
     */
    @ApiOperation("正常修改密码")
    @GetMapping("/updatePswd")
    public JsonResult updatePswd(@RequestBody String passWd, String passWord){
        User user = (User) session.getAttribute("user");
        //原始密码加密判断
        String statrPassword = new SimpleHash("md5",passWd,ByteSource.Util.bytes(user.getUserName()),5).toString();
        //判断用户输入的原始密码是否正确
        if (user.getPassword().equals(statrPassword)){
            System.out.println("用户加密前的密码："+passWord);
            String pswd = new SimpleHash("md5",passWord, ByteSource.Util.bytes(user.getUserName()),5).toString();
            user.setPassword(pswd);
            boolean user_name = iUserService.update(user, new QueryWrapper<User>().eq("user_name", user.getUserName()));
           return new JsonResult(200,"修改密码成功",passWord);
        }
        return new JsonResult(500,"密码错误",passWd);
    }

    /**
     * @return
     */
    @ApiOperation("查询数量")
    @GetMapping("/selectNub")
  public JsonResult nub(){
      try {
          Map<String,Integer> nub = numService.nub();
          return new JsonResult(200,"查询成功",nub);
      } catch (Exception e) {
          e.printStackTrace();
          return new JsonResult(500,"查询失败","");
      }
  }

    /**
     * @apiNote 查询用户的信息
     * @param userId  用户id
     * @return
     */
  @ApiOperation("查询用户的信息")
  @GetMapping("/selectList")
   public JsonResult selectList(int userId){
      try {
          User user = iUserService.getOne(new QueryWrapper<User>().eq("user_id", userId));
          return new JsonResult(200,"查询成功",user);
      } catch (Exception e) {
          e.printStackTrace();
          return  new JsonResult(500,"查询失败","");
      }
  }
    /**
     * @apiNote 修改用户的昵称
     */
    @ApiOperation("修改用户的昵称")
   @GetMapping("updateUserName")
        public JsonResult updateUserName(String userName){
       User user = (User) session.getAttribute("user");
       String getfilter = numService.getfilter(userName);
       if (!getfilter.equals(userName)){
           System.out.println("请勿输入敏感词汇");
           return new JsonResult(500,"请勿输入敏感词汇",user.getUserName());
       }
       user.setUserName(userName);
       try {
           iUserService.update(user,new QueryWrapper<User>().eq("user_id",user.getUserId()));
           return new JsonResult(200,"修改昵称成功",userName);
       } catch (Exception e) {
           e.printStackTrace();
           return new JsonResult(500,"修改昵称失败",user.getUserName());
       }
   }

}
